﻿using DifyToOpenAI.Common;
using DifyToOpenAI.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using System.Net.Mime;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace DifyToOpenAI.Controllers
{
    [Authorize] // 需要认证的控制器或方法
    [ApiController]
    //[Route("v1/[controller]")] // 这会将路径设置为 /v1/Models
    [Route("v1/models")] // 这会将路径设置为 /v1/Models

    public class ModelsController : ControllerBase
    {
        private readonly ILogger<ModelsController> _logger;

        public ModelsController(ILogger<ModelsController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 获取所有可用模型列表。
        /// 兼容 OpenAI API /v1/models 协议。
        /// </summary>
        [HttpGet] // 对应 GET /v1/models
        public IActionResult ListModels()
        {
            // 这里应该从你的数据源获取模型数据
            // 并将其映射到兼容 OpenAI 协议的响应格式

            ModelList initmodelList = ApplicationContext.initmodelList;

            string modelsjson = string.Empty;
            ContentResult resContent;

            try
            {
                if (initmodelList == null|| initmodelList.data!.Count<=0)
                {
                    // 如果数据不存在是预期行为，可以返回 NotFound
                    // return NotFound(new { error = "模型列表未初始化或不存在。" });

                    // 如果这是一个不该发生的错误，则抛出异常让 catch 捕获
                    throw new InvalidOperationException("模型列表 (initmodelList) 未被初始化。");
                }
                modelsjson = JsonSerializer.Serialize(initmodelList, ApplicationContext.jsonSerializerOptions);
                resContent = Content(modelsjson, MediaTypeNames.Application.Json, Encoding.UTF8);
                resContent.StatusCode = 200;
            }
            catch (Exception ex)
            {
                //JsonObject errorobj = new JsonObject();
                //errorobj.Add("error", ex.Message);
                var errorPayload = new { error = ex.Message };
                modelsjson = JsonSerializer.Serialize(errorPayload, ApplicationContext.jsonSerializerOptions);
                resContent = Content(modelsjson.ToString()!, MediaTypeNames.Application.Json, Encoding.UTF8);
                resContent.StatusCode = 400;
                //throw;
            }
           

            #region 记录日志
            LogHelperServices.CommonApiResponseLog(_logger, this, resContent);
            #endregion


            return resContent;

            #region NOTE 作废
            //try
            //{

            //    string ipAddress = HttpContext.Connection.RemoteIpAddress!.ToString();
            //    string requestLine = Request.Method + " " + Request.GetDisplayUrl() + " " + Request.Protocol;
            //    StringBuilder stringBuilderlog= new StringBuilder();
            //    stringBuilderlog.AppendLine("");
            //    stringBuilderlog.AppendLine("Form IpAddress: " + ipAddress);
            //    stringBuilderlog.AppendLine("Request Url: " + requestLine);
            //    stringBuilderlog.AppendLine("Response StatusCode: " + resContent.StatusCode);
            //    stringBuilderlog.AppendLine("Response Body: " + resContent.Content);
            //    _logger.LogInformation(stringBuilderlog.ToString());
            //}
            //catch (Exception)
            //{

            //    // throw;
            //}
            #endregion
        }

        /// <summary>
        /// 根据模型ID获取特定模型信息。
        /// 兼容 OpenAI API /v1/models/{model} 协议。
        /// </summary>
        [HttpGet("{modelId}")] // 对应 GET /v1/models/{modelId}
        public IActionResult GetModelById(string modelId)
        {
            List<ModelData> modelDatas = ApplicationContext.initmodelList.data!;
            // 使用 LINQ 的 FirstOrDefault 方法查找
            // model => model.id == targetId 是一个 Lambda 表达式，它定义了筛选条件
            ModelData? foundModel = modelDatas.FirstOrDefault(model => model.id == modelId);
            // 检查是否找到了模型
            string modelsjson = string.Empty;
            ContentResult resContent;
            if (foundModel != null)
            {
                // 找到了，您可以在这里使用 foundModel 对象
                modelsjson = JsonSerializer.Serialize(foundModel, ApplicationContext.jsonSerializerOptions);
                resContent = Content(modelsjson, MediaTypeNames.Application.Json, Encoding.UTF8);
                resContent.StatusCode = 200;
            }
            else
            {  // 在列表中没有找到 id 为 "" 的模型
                JsonObject jsonobj= new JsonObject();
                JsonObject errorobj = new JsonObject();
                errorobj.Add("message", "Model with identifier '"+ modelId + "' not found");
                errorobj.Add("type", "invalid_request_error");
                errorobj.Add("param", null);
                errorobj.Add("code", "400");
                jsonobj.Add("error", errorobj);
                modelsjson = JsonSerializer.Serialize(jsonobj, ApplicationContext.jsonSerializerOptions);
                resContent = Content(modelsjson, MediaTypeNames.Application.Json, Encoding.UTF8);
                resContent.StatusCode = 400;
              
            }

            #region 记录日志
            LogHelperServices.CommonApiResponseLog(_logger, this, resContent);
            #endregion
            return resContent;
        }
    }
}
